package com.erebus.controller;


import com.erebus.feignclient.AuthServiceClient;
import com.erebus.feignclient.ShopCartClient;
import com.erebus.model.dto.Cart;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.base.model.RestResponse;
import com.taobao.base.model.TokenResponse;
import com.taobao.base.model.TokenUser;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@CrossOrigin // 允许跨域

public class api {

    @Autowired
    private ShopCartClient shopCartClient;
    @Autowired
    private AuthServiceClient authServiceClient;

    @Autowired
    private ObjectMapper objectMapper;

    // test
    @GetMapping("/test")
    public RestResponse<List<Cart>> test(int userId)  {
// 从请求头中获取 Authorization 字段
//        TokenUser tokenUser = null;
//         tokenUser = getTokenUser(request);

        RestResponse<List<Cart>> restResponse = shopCartClient.getCart(userId);



        return restResponse;
    }

    /**
     * 解析token 获取用户信息
     */
    private TokenUser getTokenUser(HttpServletRequest request) {
        // 从请求头中获取 Authorization 字段
        TokenUser tokenUser = null;
        String authorizationHeader = request.getHeader("Authorization");
        // 检查是否包含 Bearer Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            TokenResponse tokenResponse = authServiceClient.checkToken(token);
            String jsonString = tokenResponse.getUser_name();
            // 转TokeUser对象
            try {
                tokenUser = objectMapper.readValue(jsonString, TokenUser.class);
                System.out.println(tokenUser);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenUser;
    }
}
